function [trl, event] = trlfun_decperc(cfg)

% experiment:
% -----------
% Subjects view stimuli of different categories (30 per category, 120 
% stimuli total, 4 blocked repeats). The task is to attend and
% press a button when fixation dot turns red. Stimuli are normalized for
% luminance and spatial frequency.

% trial structure:
% ----------------
% iti: 2000ms (trigger: 1) 
% stimulus: 2000ms (trigger: stimnr + 100) 
% delay: 200ms (trigger: stimcategory 201-204, see below)
% [PROBLEM: OVERLAP WITH STIMULUS CODES!]
% mask: 200ms (trigger: 99) 
%
% ~10% response trials.Color change can occur only during iti or stimulus 
% (random onset). Therefore, selecting trials based on mask trigger 
% automatically excludes response trials (as is being done with by this 
% function).
%
% stimulus category codes: 
% ------------------------
% 201 = face 
% 202 = scene 
% 203 = body 
% 204 = tool 
%

%% define trials

% extract hdr and event info
hdr   = ft_read_header(cfg.dataset);
event = ft_read_event(cfg.dataset);

% search for trigger events
value    = [event(strcmp('UPPT001', {event.type})).value]';
sample   = [event(strcmp('UPPT001', {event.type})).sample]';

% determine number of samples before and after trigger
PreTrig             = -round(  (-4.2)  *  hdr.Fs);
PostTrig            =  round(  (0.8)   *  hdr.Fs);
BeamerCorrection    =  round(  0.05  *  hdr.Fs);

% define trials based on triggers and create custom trl matrix
trl = [];

for i=1:length(value) % loop over all events
    
    if value(i) == 99  &&  value(i-1) ~= 99
        
        % define time interval
        BegSample     = sample(i) - PreTrig + BeamerCorrection;
        EndSample     = sample(i) + PostTrig + BeamerCorrection;
        Offset        = -round(2.0  *  hdr.Fs); % @ stimlus onset 
        Condition     = value(i-1);
        
        % creat trl matrix, condition in 4th column that will later be in
        % data.trialinfo structure
        trl(end+1, :) = round([BegSample EndSample Offset Condition]);
        
    end
end

% sort trl matrix on sample number to prevent rejection bias
% this step is only important when selecting on condition (which is not
% done by the function in its current state). Still include the last line
% to be sure.
trl = sortrows(trl, 1);

end
